{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "'''\n",
    "A Convolutional Network implementation example using TensorFlow library.\n",
    "This example is using the MNIST database of handwritten digits\n",
    "(http://yann.lecun.com/exdb/mnist/)\n",
    "\n",
    "Author: Aymeric Damien\n",
    "Project: https://github.com/aymericdamien/TensorFlow-Examples/\n",
    "'''"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Extracting /tmp/data/train-images-idx3-ubyte.gz\n",
      "Extracting /tmp/data/train-labels-idx1-ubyte.gz\n",
      "Extracting /tmp/data/t10k-images-idx3-ubyte.gz\n",
      "Extracting /tmp/data/t10k-labels-idx1-ubyte.gz\n"
     ]
    }
   ],
   "source": [
    "import tensorflow as tf\n",
    "\n",
    "# Import MNIST data\n",
    "from tensorflow.examples.tutorials.mnist import input_data\n",
    "mnist = input_data.read_data_sets(\"/tmp/data/\", one_hot=True)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "# Parameters\n",
    "learning_rate = 0.001\n",
    "training_iters = 200000\n",
    "batch_size = 128\n",
    "display_step = 10\n",
    "\n",
    "# Network Parameters\n",
    "n_input = 784 # MNIST data input (img shape: 28*28)\n",
    "n_classes = 10 # MNIST total classes (0-9 digits)\n",
    "dropout = 0.75 # Dropout, probability to keep units\n",
    "\n",
    "# tf Graph input\n",
    "x = tf.placeholder(tf.float32, [None, n_input])\n",
    "y = tf.placeholder(tf.float32, [None, n_classes])\n",
    "keep_prob = tf.placeholder(tf.float32) #dropout (keep probability)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "# Create some wrappers for simplicity\n",
    "def conv2d(x, W, b, strides=1):\n",
    "    # Conv2D wrapper, with bias and relu activation\n",
    "    x = tf.nn.conv2d(x, W, strides=[1, strides, strides, 1], padding='SAME')\n",
    "    x = tf.nn.bias_add(x, b)\n",
    "    return tf.nn.relu(x)\n",
    "\n",
    "\n",
    "def maxpool2d(x, k=2):\n",
    "    # MaxPool2D wrapper\n",
    "    return tf.nn.max_pool(x, ksize=[1, k, k, 1], strides=[1, k, k, 1],\n",
    "                          padding='SAME')\n",
    "\n",
    "\n",
    "# Create model\n",
    "def conv_net(x, weights, biases, dropout):\n",
    "    # Reshape input picture\n",
    "    x = tf.reshape(x, shape=[-1, 28, 28, 1])\n",
    "\n",
    "    # Convolution Layer\n",
    "    conv1 = conv2d(x, weights['wc1'], biases['bc1'])\n",
    "    # Max Pooling (down-sampling)\n",
    "    conv1 = maxpool2d(conv1, k=2)\n",
    "\n",
    "    # Convolution Layer\n",
    "    conv2 = conv2d(conv1, weights['wc2'], biases['bc2'])\n",
    "    # Max Pooling (down-sampling)\n",
    "    conv2 = maxpool2d(conv2, k=2)\n",
    "\n",
    "    # Fully connected layer\n",
    "    # Reshape conv2 output to fit fully connected layer input\n",
    "    fc1 = tf.reshape(conv2, [-1, weights['wd1'].get_shape().as_list()[0]])\n",
    "    fc1 = tf.add(tf.matmul(fc1, weights['wd1']), biases['bd1'])\n",
    "    fc1 = tf.nn.relu(fc1)\n",
    "    # Apply Dropout\n",
    "    fc1 = tf.nn.dropout(fc1, dropout)\n",
    "\n",
    "    # Output, class prediction\n",
    "    out = tf.add(tf.matmul(fc1, weights['out']), biases['out'])\n",
    "    return out"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "# Store layers weight & bias\n",
    "weights = {\n",
    "    # 5x5 conv, 1 input, 32 outputs\n",
    "    'wc1': tf.Variable(tf.random_normal([5, 5, 1, 32])),\n",
    "    # 5x5 conv, 32 inputs, 64 outputs\n",
    "    'wc2': tf.Variable(tf.random_normal([5, 5, 32, 64])),\n",
    "    # fully connected, 7*7*64 inputs, 1024 outputs\n",
    "    'wd1': tf.Variable(tf.random_normal([7*7*64, 1024])),\n",
    "    # 1024 inputs, 10 outputs (class prediction)\n",
    "    'out': tf.Variable(tf.random_normal([1024, n_classes]))\n",
    "}\n",
    "\n",
    "biases = {\n",
    "    'bc1': tf.Variable(tf.random_normal([32])),\n",
    "    'bc2': tf.Variable(tf.random_normal([64])),\n",
    "    'bd1': tf.Variable(tf.random_normal([1024])),\n",
    "    'out': tf.Variable(tf.random_normal([n_classes]))\n",
    "}\n",
    "\n",
    "# Construct model\n",
    "pred = conv_net(x, weights, biases, keep_prob)\n",
    "\n",
    "# Define loss and optimizer\n",
    "cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(pred, y))\n",
    "optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate).minimize(cost)\n",
    "\n",
    "# Evaluate model\n",
    "correct_pred = tf.equal(tf.argmax(pred, 1), tf.argmax(y, 1))\n",
    "accuracy = tf.reduce_mean(tf.cast(correct_pred, tf.float32))\n",
    "\n",
    "# Initializing the variables\n",
    "init = tf.initialize_all_variables()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Iter 1280, Minibatch Loss= 17231.589844, Training Accuracy= 0.25000\n",
      "Iter 2560, Minibatch Loss= 10580.260742, Training Accuracy= 0.54688\n",
      "Iter 3840, Minibatch Loss= 7395.362793, Training Accuracy= 0.64062\n",
      "Iter 5120, Minibatch Loss= 4864.292480, Training Accuracy= 0.75781\n",
      "Iter 6400, Minibatch Loss= 3830.062012, Training Accuracy= 0.80469\n",
      "Iter 7680, Minibatch Loss= 6031.701172, Training Accuracy= 0.72656\n",
      "Iter 8960, Minibatch Loss= 2549.708740, Training Accuracy= 0.81250\n",
      "Iter 10240, Minibatch Loss= 2010.484985, Training Accuracy= 0.84375\n",
      "Iter 11520, Minibatch Loss= 1607.380981, Training Accuracy= 0.89062\n",
      "Iter 12800, Minibatch Loss= 1983.302856, Training Accuracy= 0.82812\n",
      "Iter 14080, Minibatch Loss= 401.215088, Training Accuracy= 0.94531\n",
      "Iter 15360, Minibatch Loss= 976.289307, Training Accuracy= 0.95312\n",
      "Iter 16640, Minibatch Loss= 1844.699951, Training Accuracy= 0.89844\n",
      "Iter 17920, Minibatch Loss= 1009.859863, Training Accuracy= 0.92969\n",
      "Iter 19200, Minibatch Loss= 1397.939453, Training Accuracy= 0.88281\n",
      "Iter 20480, Minibatch Loss= 540.369995, Training Accuracy= 0.96094\n",
      "Iter 21760, Minibatch Loss= 2589.246826, Training Accuracy= 0.87500\n",
      "Iter 23040, Minibatch Loss= 404.981293, Training Accuracy= 0.96094\n",
      "Iter 24320, Minibatch Loss= 742.155396, Training Accuracy= 0.93750\n",
      "Iter 25600, Minibatch Loss= 851.599731, Training Accuracy= 0.93750\n",
      "Iter 26880, Minibatch Loss= 1527.609619, Training Accuracy= 0.90625\n",
      "Iter 28160, Minibatch Loss= 1209.633301, Training Accuracy= 0.91406\n",
      "Iter 29440, Minibatch Loss= 1123.146851, Training Accuracy= 0.93750\n",
      "Iter 30720, Minibatch Loss= 950.860596, Training Accuracy= 0.92188\n",
      "Iter 32000, Minibatch Loss= 1217.373779, Training Accuracy= 0.92188\n",
      "Iter 33280, Minibatch Loss= 859.433105, Training Accuracy= 0.91406\n",
      "Iter 34560, Minibatch Loss= 487.426331, Training Accuracy= 0.95312\n",
      "Iter 35840, Minibatch Loss= 287.507721, Training Accuracy= 0.96875\n",
      "Iter 37120, Minibatch Loss= 786.797485, Training Accuracy= 0.91406\n",
      "Iter 38400, Minibatch Loss= 248.981216, Training Accuracy= 0.97656\n",
      "Iter 39680, Minibatch Loss= 147.081467, Training Accuracy= 0.97656\n",
      "Iter 40960, Minibatch Loss= 1198.459106, Training Accuracy= 0.93750\n",
      "Iter 42240, Minibatch Loss= 717.058716, Training Accuracy= 0.92188\n",
      "Iter 43520, Minibatch Loss= 351.870453, Training Accuracy= 0.96094\n",
      "Iter 44800, Minibatch Loss= 271.505554, Training Accuracy= 0.96875\n",
      "Iter 46080, Minibatch Loss= 0.000000, Training Accuracy= 1.00000\n",
      "Iter 47360, Minibatch Loss= 806.163818, Training Accuracy= 0.95312\n",
      "Iter 48640, Minibatch Loss= 1055.359009, Training Accuracy= 0.91406\n",
      "Iter 49920, Minibatch Loss= 459.845520, Training Accuracy= 0.94531\n",
      "Iter 51200, Minibatch Loss= 133.995087, Training Accuracy= 0.97656\n",
      "Iter 52480, Minibatch Loss= 378.886780, Training Accuracy= 0.96094\n",
      "Iter 53760, Minibatch Loss= 122.112671, Training Accuracy= 0.98438\n",
      "Iter 55040, Minibatch Loss= 357.410950, Training Accuracy= 0.96875\n",
      "Iter 56320, Minibatch Loss= 164.791595, Training Accuracy= 0.98438\n",
      "Iter 57600, Minibatch Loss= 740.711060, Training Accuracy= 0.95312\n",
      "Iter 58880, Minibatch Loss= 755.948364, Training Accuracy= 0.92969\n",
      "Iter 60160, Minibatch Loss= 289.819153, Training Accuracy= 0.94531\n",
      "Iter 61440, Minibatch Loss= 162.940323, Training Accuracy= 0.96875\n",
      "Iter 62720, Minibatch Loss= 616.192200, Training Accuracy= 0.92969\n",
      "Iter 64000, Minibatch Loss= 649.317993, Training Accuracy= 0.92188\n",
      "Iter 65280, Minibatch Loss= 1021.529785, Training Accuracy= 0.93750\n",
      "Iter 66560, Minibatch Loss= 203.839050, Training Accuracy= 0.96094\n",
      "Iter 67840, Minibatch Loss= 469.755249, Training Accuracy= 0.96094\n",
      "Iter 69120, Minibatch Loss= 36.496567, Training Accuracy= 0.98438\n",
      "Iter 70400, Minibatch Loss= 214.677551, Training Accuracy= 0.95312\n",
      "Iter 71680, Minibatch Loss= 115.657990, Training Accuracy= 0.96875\n",
      "Iter 72960, Minibatch Loss= 354.555115, Training Accuracy= 0.96875\n",
      "Iter 74240, Minibatch Loss= 124.091103, Training Accuracy= 0.97656\n",
      "Iter 75520, Minibatch Loss= 614.557251, Training Accuracy= 0.94531\n",
      "Iter 76800, Minibatch Loss= 343.182983, Training Accuracy= 0.95312\n",
      "Iter 78080, Minibatch Loss= 678.875183, Training Accuracy= 0.94531\n",
      "Iter 79360, Minibatch Loss= 313.656494, Training Accuracy= 0.95312\n",
      "Iter 80640, Minibatch Loss= 169.024185, Training Accuracy= 0.96094\n",
      "Iter 81920, Minibatch Loss= 98.455017, Training Accuracy= 0.96875\n",
      "Iter 83200, Minibatch Loss= 359.754517, Training Accuracy= 0.92188\n",
      "Iter 84480, Minibatch Loss= 214.993103, Training Accuracy= 0.96875\n",
      "Iter 85760, Minibatch Loss= 262.921265, Training Accuracy= 0.97656\n",
      "Iter 87040, Minibatch Loss= 558.218445, Training Accuracy= 0.89844\n",
      "Iter 88320, Minibatch Loss= 122.281952, Training Accuracy= 0.99219\n",
      "Iter 89600, Minibatch Loss= 300.606689, Training Accuracy= 0.93750\n",
      "Iter 90880, Minibatch Loss= 261.051025, Training Accuracy= 0.98438\n",
      "Iter 92160, Minibatch Loss= 59.812164, Training Accuracy= 0.98438\n",
      "Iter 93440, Minibatch Loss= 309.307312, Training Accuracy= 0.96875\n",
      "Iter 94720, Minibatch Loss= 626.035706, Training Accuracy= 0.95312\n",
      "Iter 96000, Minibatch Loss= 317.929260, Training Accuracy= 0.96875\n",
      "Iter 97280, Minibatch Loss= 196.908218, Training Accuracy= 0.97656\n",
      "Iter 98560, Minibatch Loss= 843.143250, Training Accuracy= 0.95312\n",
      "Iter 99840, Minibatch Loss= 389.142761, Training Accuracy= 0.96875\n",
      "Iter 101120, Minibatch Loss= 246.468994, Training Accuracy= 0.96094\n",
      "Iter 102400, Minibatch Loss= 110.580948, Training Accuracy= 0.98438\n",
      "Iter 103680, Minibatch Loss= 208.350586, Training Accuracy= 0.96875\n",
      "Iter 104960, Minibatch Loss= 506.229462, Training Accuracy= 0.94531\n",
      "Iter 106240, Minibatch Loss= 49.548233, Training Accuracy= 0.98438\n",
      "Iter 107520, Minibatch Loss= 728.496582, Training Accuracy= 0.92969\n",
      "Iter 108800, Minibatch Loss= 187.256622, Training Accuracy= 0.97656\n",
      "Iter 110080, Minibatch Loss= 273.696899, Training Accuracy= 0.97656\n",
      "Iter 111360, Minibatch Loss= 317.126678, Training Accuracy= 0.96094\n",
      "Iter 112640, Minibatch Loss= 148.293365, Training Accuracy= 0.98438\n",
      "Iter 113920, Minibatch Loss= 139.360168, Training Accuracy= 0.97656\n",
      "Iter 115200, Minibatch Loss= 167.539093, Training Accuracy= 0.98438\n",
      "Iter 116480, Minibatch Loss= 565.433594, Training Accuracy= 0.94531\n",
      "Iter 117760, Minibatch Loss= 8.117203, Training Accuracy= 0.99219\n",
      "Iter 119040, Minibatch Loss= 348.071472, Training Accuracy= 0.96875\n",
      "Iter 120320, Minibatch Loss= 287.732849, Training Accuracy= 0.97656\n",
      "Iter 121600, Minibatch Loss= 156.525284, Training Accuracy= 0.96875\n",
      "Iter 122880, Minibatch Loss= 296.147339, Training Accuracy= 0.98438\n",
      "Iter 124160, Minibatch Loss= 260.941956, Training Accuracy= 0.98438\n",
      "Iter 125440, Minibatch Loss= 241.011719, Training Accuracy= 0.98438\n",
      "Iter 126720, Minibatch Loss= 185.330444, Training Accuracy= 0.98438\n",
      "Iter 128000, Minibatch Loss= 346.407013, Training Accuracy= 0.96875\n",
      "Iter 129280, Minibatch Loss= 522.477173, Training Accuracy= 0.94531\n",
      "Iter 130560, Minibatch Loss= 97.665955, Training Accuracy= 0.96094\n",
      "Iter 131840, Minibatch Loss= 111.370262, Training Accuracy= 0.96875\n",
      "Iter 133120, Minibatch Loss= 106.377136, Training Accuracy= 0.97656\n",
      "Iter 134400, Minibatch Loss= 432.294983, Training Accuracy= 0.96094\n",
      "Iter 135680, Minibatch Loss= 104.584610, Training Accuracy= 0.98438\n",
      "Iter 136960, Minibatch Loss= 439.611053, Training Accuracy= 0.95312\n",
      "Iter 138240, Minibatch Loss= 171.394562, Training Accuracy= 0.96875\n",
      "Iter 139520, Minibatch Loss= 83.505905, Training Accuracy= 0.98438\n",
      "Iter 140800, Minibatch Loss= 240.278427, Training Accuracy= 0.98438\n",
      "Iter 142080, Minibatch Loss= 417.140320, Training Accuracy= 0.96094\n",
      "Iter 143360, Minibatch Loss= 77.656067, Training Accuracy= 0.97656\n",
      "Iter 144640, Minibatch Loss= 284.589844, Training Accuracy= 0.97656\n",
      "Iter 145920, Minibatch Loss= 372.114288, Training Accuracy= 0.96875\n",
      "Iter 147200, Minibatch Loss= 352.900024, Training Accuracy= 0.96094\n",
      "Iter 148480, Minibatch Loss= 148.120621, Training Accuracy= 0.97656\n",
      "Iter 149760, Minibatch Loss= 127.385742, Training Accuracy= 0.98438\n",
      "Iter 151040, Minibatch Loss= 383.167175, Training Accuracy= 0.96094\n",
      "Iter 152320, Minibatch Loss= 331.846649, Training Accuracy= 0.94531\n",
      "Iter 153600, Minibatch Loss= 0.000000, Training Accuracy= 1.00000\n",
      "Iter 154880, Minibatch Loss= 24.065147, Training Accuracy= 0.99219\n",
      "Iter 156160, Minibatch Loss= 43.433868, Training Accuracy= 0.99219\n",
      "Iter 157440, Minibatch Loss= 205.383972, Training Accuracy= 0.96875\n",
      "Iter 158720, Minibatch Loss= 83.019257, Training Accuracy= 0.97656\n",
      "Iter 160000, Minibatch Loss= 195.710556, Training Accuracy= 0.96875\n",
      "Iter 161280, Minibatch Loss= 177.192932, Training Accuracy= 0.95312\n",
      "Iter 162560, Minibatch Loss= 261.618713, Training Accuracy= 0.96875\n",
      "Iter 163840, Minibatch Loss= 0.000000, Training Accuracy= 1.00000\n",
      "Iter 165120, Minibatch Loss= 62.901100, Training Accuracy= 0.97656\n",
      "Iter 166400, Minibatch Loss= 17.181839, Training Accuracy= 0.98438\n",
      "Iter 167680, Minibatch Loss= 102.738960, Training Accuracy= 0.96875\n",
      "Iter 168960, Minibatch Loss= 0.000000, Training Accuracy= 1.00000\n",
      "Iter 170240, Minibatch Loss= 71.784363, Training Accuracy= 0.99219\n",
      "Iter 171520, Minibatch Loss= 260.672852, Training Accuracy= 0.96875\n",
      "Iter 172800, Minibatch Loss= 186.616119, Training Accuracy= 0.96094\n",
      "Iter 174080, Minibatch Loss= 312.432312, Training Accuracy= 0.96875\n",
      "Iter 175360, Minibatch Loss= 45.828953, Training Accuracy= 0.99219\n",
      "Iter 176640, Minibatch Loss= 62.931808, Training Accuracy= 0.98438\n",
      "Iter 177920, Minibatch Loss= 63.452362, Training Accuracy= 0.97656\n",
      "Iter 179200, Minibatch Loss= 53.608818, Training Accuracy= 0.98438\n",
      "Iter 180480, Minibatch Loss= 57.089508, Training Accuracy= 0.97656\n",
      "Iter 181760, Minibatch Loss= 601.268799, Training Accuracy= 0.93750\n",
      "Iter 183040, Minibatch Loss= 59.850044, Training Accuracy= 0.97656\n",
      "Iter 184320, Minibatch Loss= 145.267883, Training Accuracy= 0.96875\n",
      "Iter 185600, Minibatch Loss= 24.205322, Training Accuracy= 0.99219\n",
      "Iter 186880, Minibatch Loss= 51.866646, Training Accuracy= 0.98438\n",
      "Iter 188160, Minibatch Loss= 166.911987, Training Accuracy= 0.96875\n",
      "Iter 189440, Minibatch Loss= 32.308147, Training Accuracy= 0.98438\n",
      "Iter 190720, Minibatch Loss= 514.898071, Training Accuracy= 0.92188\n",
      "Iter 192000, Minibatch Loss= 146.610031, Training Accuracy= 0.98438\n",
      "Iter 193280, Minibatch Loss= 23.939758, Training Accuracy= 0.99219\n",
      "Iter 194560, Minibatch Loss= 224.806641, Training Accuracy= 0.97656\n",
      "Iter 195840, Minibatch Loss= 71.935089, Training Accuracy= 0.98438\n",
      "Iter 197120, Minibatch Loss= 182.021210, Training Accuracy= 0.96875\n",
      "Iter 198400, Minibatch Loss= 125.573784, Training Accuracy= 0.96875\n",
      "Iter 199680, Minibatch Loss= 122.506104, Training Accuracy= 0.96875\n",
      "Optimization Finished!\n",
      "Testing Accuracy: 0.972656\n"
     ]
    }
   ],
   "source": [
    "# Launch the graph\n",
    "with tf.Session() as sess:\n",
    "    sess.run(init)\n",
    "    step = 1\n",
    "    # Keep training until reach max iterations\n",
    "    while step * batch_size < training_iters:\n",
    "        batch_x, batch_y = mnist.train.next_batch(batch_size)\n",
    "        # Run optimization op (backprop)\n",
    "        sess.run(optimizer, feed_dict={x: batch_x, y: batch_y,\n",
    "                                       keep_prob: dropout})\n",
    "        if step % display_step == 0:\n",
    "            # Calculate batch loss and accuracy\n",
    "            loss, acc = sess.run([cost, accuracy], feed_dict={x: batch_x,\n",
    "                                                              y: batch_y,\n",
    "                                                              keep_prob: 1.})\n",
    "            print \"Iter \" + str(step*batch_size) + \", Minibatch Loss= \" + \\\n",
    "                  \"{:.6f}\".format(loss) + \", Training Accuracy= \" + \\\n",
    "                  \"{:.5f}\".format(acc)\n",
    "        step += 1\n",
    "    print \"Optimization Finished!\"\n",
    "\n",
    "    # Calculate accuracy for 256 mnist test images\n",
    "    print \"Testing Accuracy:\", \\\n",
    "        sess.run(accuracy, feed_dict={x: mnist.test.images[:256],\n",
    "                                      y: mnist.test.labels[:256],\n",
    "                                      keep_prob: 1.})"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 2",
   "language": "python",
   "name": "python2"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 2.0
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython2",
   "version": "2.7.11"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 0
}
